//
//  EmoticonInputView.m
//  微博表情键盘
//
//  Created by zxy on 2019/8/12.
//  Copyright © 2019 zxy. All rights reserved.
//

#import "EmoticonInputView.h"
#import "EmoticonCell.h"
#import "FlyHorizontalFlowLauyout.h"
#define emoticonCellHeight 50 //表情cell高度
#define Espace 10 //sectionInset左右间距
#define bottomTooBarHeight 35 //底部toolBar高度
#define EmoticonPageMaxNumber 20  //每页最大显示表情数量
static NSString *const EmoticonCellReuseIdentifier = @"EmoticonCellReuseIdentifier";
@interface EmoticonInputView()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>{
    NSInteger _clickGroupIndex;//点击表情分组下标
    UIButton *_oldBtn;//保持底部toolBar按钮
    NSInteger totalSectionNumber;//每个分组表情组数量
}
@property(nonatomic,strong)UICollectionView *emoticonCollectionView;
@property(nonatomic,strong)UIView *pageControllBgView;
@property(nonatomic,strong)UIView *bottomToolBarView;
@property(nonatomic,strong)NSArray *emoticonArr;
@end
@implementation EmoticonInputView

+(instancetype)sharedEmInputView{
    static EmoticonInputView *v;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        v = [EmoticonInputView new];
    });
    return v;
}


-(UICollectionView *)emoticonCollectionView{
    if(!_emoticonCollectionView){
        CGFloat itemWidth = (self.bounds.size.width - Espace * 2)/ 7.0;
        FlyHorizontalFlowLauyout *layout = [[FlyHorizontalFlowLauyout alloc]init];
        layout.itemSize = CGSizeMake(itemWidth, emoticonCellHeight);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.sectionInset = UIEdgeInsetsMake(0, Espace, 0, Espace);
        _emoticonCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,emoticonCellHeight * 3) collectionViewLayout:layout];
        _emoticonCollectionView.backgroundColor = self.backgroundColor;
        _emoticonCollectionView.delegate = self;
        _emoticonCollectionView.dataSource = self;
        _emoticonCollectionView.showsHorizontalScrollIndicator = NO;
        _emoticonCollectionView.pagingEnabled = YES;
        _emoticonCollectionView.top = 5;
        [_emoticonCollectionView registerClass:[EmoticonCell class] forCellWithReuseIdentifier:EmoticonCellReuseIdentifier];
        
    }
    return _emoticonCollectionView;
}

-(UIView *)pageControllBgView{
    if(!_pageControllBgView){
        _pageControllBgView = [[UIView alloc]initWithFrame:CGRectMake(0, _emoticonCollectionView.bottom, self.bounds.size.width, 20)];
    }
    return _pageControllBgView;
}

-(UIView *)bottomToolBarView{
    if(!_bottomToolBarView){
        CGFloat btnW = self.bounds.size.width / 3.0;
        NSArray *titles = @[@"默认",@"Emoji",@"浪小花"];
        NSArray *imageNormal = @[@"compose_emotion_table_left_normal",@"compose_emotion_table_mid_normal",@"compose_emotion_table_right_normal"];
        NSArray *imageSel = @[@"compose_emotion_table_left_selected",@"compose_emotion_table_mid_selected",@"compose_emotion_table_right_selected"];
        _bottomToolBarView = [[UIView alloc]initWithFrame:CGRectMake(0, _pageControllBgView.bottom, SCREEN_WIDTH, bottomTooBarHeight)];
        for (NSInteger i = 0; i < 3; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(i * btnW, 0, btnW, bottomTooBarHeight);
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
            UIImage *normImage = [XHHelper imageFromBundleName:@"ResourceWeibo" imageName:imageNormal[i]];
            UIImage *selImage = [XHHelper imageFromBundleName:@"ResourceWeibo" imageName:imageSel[i]];
            [btn setBackgroundImage:[normImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, normImage.size.width - 1) resizingMode:UIImageResizingModeStretch] forState:UIControlStateNormal];
            [btn setBackgroundImage:[selImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, selImage.size.width - 1) resizingMode:UIImageResizingModeStretch]  forState:UIControlStateSelected];
            if(i == 0 ){
                _oldBtn = btn;
                btn.selected = YES;
            }
            btn.tag = i;
            [_bottomToolBarView addSubview:btn];
            [btn addTarget:self action:@selector(bottomToolBarBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return _bottomToolBarView;
}

#pragma mark -底部toolBar按钮点击事件
-(void)bottomToolBarBtnClick:(UIButton *)sender{
    _oldBtn.selected = NO;
    sender.selected = YES;
    _oldBtn = sender;
    _clickGroupIndex = sender.tag;
    //将内容偏移量设置为0
    [self.emoticonCollectionView setContentOffset:CGPointZero animated:NO];
    [self createPageControler];
    
    //获取第一个分组表情模型
    EmoticonModel *groupM = _emoticonArr[sender.tag];
    //计算第一个分组表情组数
    totalSectionNumber = ceil(groupM.emoticons.count / (float)EmoticonPageMaxNumber);
    if(totalSectionNumber == 0)totalSectionNumber = 1;
    [self.emoticonCollectionView reloadData];
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        _clickGroupIndex = 0;
        self.backgroundColor = [UIColor whiteColor];
        self.frame = CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width,emoticonCellHeight * 3 + 55);
        [self addSubview:self.emoticonCollectionView];
        [self addSubview:self.pageControllBgView];
        [self addSubview:self.bottomToolBarView];
        //加载表情
        [self getEmoticonGroupData];
    }
    return self;
}

#pragma mark -获取表情
-(void)getEmoticonGroupData{
    _emoticonArr = [XHHelper groupEmoticons];
    
    //获取第一个分组表情模型
    EmoticonModel *groupM = _emoticonArr.firstObject;
    //计算第一个分组表情组数
    totalSectionNumber = ceil(groupM.emoticons.count / (float)EmoticonPageMaxNumber);
    if(totalSectionNumber == 0)totalSectionNumber = 1;
    NSLog(@"===%zd",totalSectionNumber);
    
    [self.emoticonCollectionView reloadData];
    [self createPageControler];
}

#pragma mark -更改pageController颜色
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / scrollView.bounds.size.width;
    [self.pageControllBgView.layer.sublayers enumerateObjectsUsingBlock:^(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //更改pageController颜色
        obj.backgroundColor = (index == idx) ? UIColorHex(fd8225).CGColor : UIColorHex(dedede).CGColor;
    }];
}

#pragma mark -创建pageController
-(void)createPageControler{
    EmoticonModel *groupM = _emoticonArr[_clickGroupIndex];
    NSArray *emticons = groupM.emoticons;
    CGFloat padding = 5, w = 6, h = 2;
    //分组表情总共页数
    NSInteger totalPage = 0;
    totalPage = ceil(emticons.count * 1.0 / EmoticonPageMaxNumber);
    //总共表情页数pageCtl总宽度,包括左右间距
    CGFloat pageControllTotalWidth = (w + 2 *padding) * totalPage;
    NSLog(@"=====%f",pageControllTotalWidth);
    [self.pageControllBgView.layer removeAllSublayers];
    for (NSInteger i = 0; i < totalPage; i++) {
        //在这里由于没有涉及到触摸事件，因此使用更加轻量级的对象
        CALayer *pageCtlLayer = [CALayer layer];
        pageCtlLayer.backgroundColor = (i == 0) ? UIColorHex(fd8225).CGColor : UIColorHex(dedede).CGColor;
        pageCtlLayer.size = CGSizeMake(w, h);
        pageCtlLayer.centerY = self.pageControllBgView.height / 2;
        pageCtlLayer.left = (self.pageControllBgView.width - pageControllTotalWidth) / 2 + i * (w + 2 * padding) + padding;
        [self.pageControllBgView.layer addSublayer:pageCtlLayer];
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return totalSectionNumber;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return EmoticonPageMaxNumber + 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EmoticonCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:EmoticonCellReuseIdentifier forIndexPath:indexPath];
    if(indexPath.item == EmoticonPageMaxNumber){
        cell.isDelete = YES;
        cell.model = nil;
    }
    else{
        EmoticonModel *groupM = _emoticonArr[_clickGroupIndex];
        cell.isDelete = NO;
        cell.groupID = groupM.groupID;
        cell.model = [self emoticonFromIndexPath:indexPath];
    }
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EmoticonCell *cell = (EmoticonCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if(cell.isDelete){//是删除按钮
        if([self.delegate respondsToSelector:@selector(emoticonInputDidTapBackspace)]){
            [self.delegate emoticonInputDidTapBackspace];
        }
    }
    else{//表情
        if([self.delegate respondsToSelector:@selector(emoticonInputDidTapText:)]){
            NSString *text = nil;
            ///图片表情
            if(cell.model.type == EmoticonTypeImage){
                ///拿到图片表情对应的文字 😄 [笑]
                text = cell.model.chs;
            }
            ///系统Emoji表情
            else if (cell.model.type == EmoticonTypeEmoji){
                NSNumber *num = [NSNumber numberWithString:cell.model.code];
                text = [NSString stringWithUTF32Char:num.unsignedIntValue];
            }
            [self.delegate emoticonInputDidTapText:text];
        }
    }
}

#pragma mark -获取表情数据
-(XHEmoticon *)emoticonFromIndexPath:(NSIndexPath *)indexPath{
    EmoticonModel *groupM = _emoticonArr[_clickGroupIndex];
    NSUInteger section = indexPath.section;
    NSInteger index = section * EmoticonPageMaxNumber + indexPath.item;
    //如果下标大于表情数组数量，将将模型返回nil
    if(index < groupM.emoticons.count){
        return groupM.emoticons[index];
    }
    return nil;
}


@end
